import React, { useState, useEffect } from 'react';
import {
  SearchOutlined,
  PlusSquareOutlined, EditOutlined, ReloadOutlined,
  DiffOutlined,
  BlockOutlined,
  UserAddOutlined,
  AppstoreOutlined,
  SelectOutlined
} from '@ant-design/icons';
import { Select, Button, Spin, Tabs, Space, Popconfirm, Input, Modal, DatePicker, Radio } from 'antd';
import {
  openNotification_util, fetchsync_util,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS,
  addkey_for_mxdata
} from '../util/util.js'
var storage = window.localStorage;
const { Option } = Select;
import { use_zyjj_initcolmun } from './use_zbzx_config.js';
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';
import ResizableTable from '../newmes/Resize_table_hook.js';
import { useLatest } from 'ahooks';
import Sortable_new from '../newmes/sortable_new.js';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

const Zyjj_list = () => {
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(false)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [columnarr, setcolumnarr] = useState(use_zyjj_initcolmun)
  const [ifshow_fb, setifshow_fb] = useState(false)
  const [fblx, setFblx] = useState("立即发布") //发布类型
  const [fbsj, setFbsj] = useState("") //发布时间
  const [ybjzsj, setYbjzsj] = useState("") //应标截止时间

  const [ifshow_fb_jj, setifshow_fb_jj] = useState(false)
  const [fblx_jj, setFblx_jj] = useState("立即发布") //竞价类型
  const [kbsj, setKbsj] = useState("") //开标时间
  const [tbjzsj, setTbjzsj] = useState("") //投标截止时间

  const [xmmc, setXmmc] = useState("")
  const [zbpl, setZbpl] = useState("")
  const xmmcRef = useLatest(xmmc)
  const zbplRef = useLatest(zbpl)

  const { setnowroute, collapsed } = useStore();

  // 时间比较工具函数
  const compareTimeWithCurrent = (targetTime, releaseType, selectedTime = null) => {
    const now = new Date();
    let compareTime;
    
    if (releaseType === '立即发布') {
      compareTime = now;
    } else if (releaseType === '定时发布' && selectedTime) {
      compareTime = new Date(selectedTime);
    } else {
      return false; // 定时发布但未选择时间
    }
    
    const target = new Date(targetTime);
    return compareTime < target;
  };


  useEffect(() => {
    querylist()
    storage[`Pc_zyjj_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_zyjj_list_${storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_zyjj_list__initsize_${storage.userid}`] ? setinitSize(storage[`Pc_zyjj_list__initsize_${storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])

  //路由跳转

  const querylist = async () => {
    setisloading(true)
    storage[`Pc_zyjj_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_zyjj_list_${storage.userid}`])) : setcolumnarr(columnarr)
    let rtdata = await fetchsync_util("/admin/zbzx/zyjj_list", 'POST', { xmmc: xmmcRef.current, zbpl: zbplRef.current }, "json")
    // openNotification_util(rtdata.rtmessage)

    rtdata.resultdata.rtdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)
      element.fbsj = element.fbsj ? convertISODateTimeToYYYYMMDDHHMMSS(element.fbsj) : ""
      element.ybjzsj = element.ybjzsj ? convertISODateTimeToYYYYMMDDHHMMSS(element.ybjzsj) : ""
      element.kbsj = element.kbsj ? convertISODateTimeToYYYYMMDDHHMMSS(element.kbsj) : ""
      element.tbjzsj = element.tbjzsj ? convertISODateTimeToYYYYMMDDHHMMSS(element.tbjzsj) : ""
    });
    setlistdata(dealnullorundenfined(rtdata.resultdata.rtdata))

    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }

  /**
   * 手动查询
   */
  const handleQuery = async () => {
    querylist()
  }
  /**
   * 新增
   */
  const handleadd = async () => {
    storage.pre_zyjj_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey('zyjj_form')
    setnowroute({ ...{ route: "/shipSRM/zbzx/zyjj_form", title: "自由竞价项目_新增" } })
  }
  /**
   * 编辑
   */
  const handleEdit = async (data, type) => {
    if (data.shzt == "待审核" || data.shzt == "审核通过") {
      openNotification_util("该项目已审核通过或已提交审核，不允许编辑！只能查看！")
      type = "view"
    }
    storage.pre_zyjj_item = JSON.stringify({ data, type })
    dropByCacheKey('zyjj_form')
    setnowroute({ ...{ route: "/shipSRM/zbzx/zyjj_form", title: "自由竞价项目_" + `${type == "edit" ? "编辑" : "查看"}` } })
  }

  /**
 * 编辑
 */
  // const handleZb = async (data) => {
  //   if (data.xmzt == "竞价结束" || data.xmzt == "竞价中") {
  //     storage.pre_xm_zb_item = JSON.stringify({ data })
  //     dropByCacheKey('xm_zb_form')
  //     setnowroute({ ...{ route: "/shipSRM/zbzx/xm_zb_form", title: "项目管理_中标" } })
  //   } else {
  //     openNotification_util("该项目未处于竞价结束或竞价中状态，无法中标设置")
  //   }

  // }

  // const handleKb = async (data) => {
  //   // console.log(data.pbkssj, data.pbjssj);
  //   if (data.zbxs == '投标' && data.xmzt == '待竞价') {
  //     storage.pre_xm_kb_item = JSON.stringify({ data })
  //     dropByCacheKey('xm_kb_form')
  //     setnowroute({ ...{ route: "/shipSRM/zbzx/xm_kb_form", title: "项目管理_淘汰" } })
  //   } else {
  //     openNotification_util("该项目未处于待竞价状态，无法进行淘汰设置")
  //   }
  // }

  /**
* 项目发起审核
*/
  const handleTjsh = async (data) => {
    if (data.xmzt != '待发布') {
      openNotification_util("该项目未处于待发布状态，无法发起审核！")
      return
    }
    if (data.shzt == '审核通过' || data.shzt == '待审核') {
      openNotification_util("该项目已审核通过或已提交审核，请勿重复提交审核！")
      return
    }
    let rtdata = await fetchsync_util("/admin/zbzx/tjsh_xm", 'POST', { id: data.id }, "json")
    openNotification_util(rtdata.rtmessage)
    querylist()
  }


  /**
 * 项目发布
 */
  const handleFb = async () => {
    if (selectedRows[0].shzt != '审核通过') {
      openNotification_util("该项目未审核通过，无法发布！")
      return
    }
    if (selectedRows[0].xmzt != '待发布') {
      openNotification_util("该项目已发布，请勿重复发布！")
      return
    }
    if (fblx == '定时发布' && fbsj == '') {
      openNotification_util("请选择发布时间！")
      return
    }
    let rtdata = await fetchsync_util("/admin/zbzx/fb_xm", 'POST', { id: selectedRows[0].id, fbsj, fblx }, "json")
    openNotification_util(rtdata.rtmessage)
    setifshow_fb(false)
    querylist()
  }

  /**
   * 项目竞价发布
   */
  const handleFb_jj = async () => {
    if (selectedRows[0].shzt != '审核通过') {
      openNotification_util("该项目未审核通过，无法发布！")
      return
    }
    if (selectedRows[0].xmzt == '竞价中' || selectedRows[0].xmzt == '竞价结束') {
      openNotification_util("该项目已处于竞价中或竞价结束状态，无法发布！")
      return
    }
    if (selectedRows[0].zbxs == '询价') {
      openNotification_util("询价项目无法进行竞价发布！")
      return
    }
    if (fblx_jj == '定时发布' && kbsj == '') {
      openNotification_util("请选择开标时间！")
      return
    }

    // 检查应标截止时间是否早于竞价发布时间
    if (selectedRows[0].ybjzsj) {
      const isBeforeDeadline = compareTimeWithCurrent(selectedRows[0].ybjzsj, fblx_jj, kbsj);
      if (isBeforeDeadline) {
        Modal.confirm({
          title: '时间确认提醒',
          content: `当前应标环节还未完全结束（应标截止时间：${selectedRows[0].ybjzsj}），确定要发布竞价吗？`,
          okText: '确定发布',
          cancelText: '取消',
          onOk: async () => {
            await executeFbJj();
          }
        });
        return;
      }
    }

    await executeFbJj();
  }

  /**
   * 执行竞价发布
   */
  const executeFbJj = async () => {
    let rtdata = await fetchsync_util("/admin/zbzx/fb_xm_jj", 'POST', { id: selectedRows[0].id, kbsj, fblx_jj }, "json")
    openNotification_util(rtdata.rtmessage)
    setifshow_fb_jj(false)
    querylist()
  }

  /**
   * 删除
   */
  const handleDelete = async (selectedRows) => {
    let rtdata = await fetchsync_util("/admin/zbzx/delete_xm", 'POST', { selectedRows }, "json")
    openNotification_util(rtdata.rtmessage)
    querylist()
  }

  const TabPaneItem = (title, listdata, columnarr, key) => {
    return <Tabs.TabPane tab={<span>{title} <span style={{
      display: 'inline-block', padding: '0 6px', fontSize: '12px', lineHeight: '14px', backgroundColor: '#a91f24',
      color: 'white', borderRadius: '8px', marginLeft: '4px'
    }}>{listdata.length}</span></span>}
      key={key}>
      {isloading ?
        (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
          <Spin /></div>)
        :
        (<ResizableTable tabledata={listdata} tablecolnum={columnarr}
          width={collapsed ? "94%" : "84%"}
          storageName={`Pc_zyjj_list_${storage.userid}`}
          czWidth={120}
          calcolor={(text) => {
            var color = "black"
            if (text == '驳回') {
              color = '#eb3617'
            }
            else if (text == '待审核') {
              color = '#3882f1'
            }
            else if (text == '审核通过') {
              color = '#1ee162'
            }
            return color
          }}
          rowCz={(record, index) => {
            var rowCz = {}
            console.log(record, "record");
            if (record.shzt == "审核通过" || record.shzt == "待审核") {
              rowCz = { showView: true}
            }
            else {
              rowCz = { showEdit: true, showView: true, showDelete: true, showTjsh: true }
            }
            return rowCz
          }}
          czMaps={{
            showView: { cz: '查看', handle: "handleView" },
            showEdit: { cz: '编辑', handle: "handleEdit" },
            showDelete: { cz: '删除', handle: "handleDelete" },
            showTjsh: { cz: '发起审核', handle: "handleTjsh" },
          }}
          showCz={{ showEdit: true, showView: true, showDelete: true, showTjsh: true }}
          sfdoubleclick="false" ifhiddencchangeselecttype="true"
          selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
          // showCz={JSON.parse(storage.anpz).find(item => item.key == "xm")?.czAnpz}
          handleEdit={(data) => handleEdit(data, "edit")}
          handleView={(data) => handleEdit(data, "view")}
          handleTjsh={(data) => handleTjsh(data)}
          scroll={{ x: 1550 }}
          handleDelete={(data) => handleDelete(data)}
          defaultPageSize={10}
          bordered
          handleselectson={(selectedRows, selectedRowKeys) => {
            setselectedRows(selectedRows)
            setselectedRowKeys(selectedRowKeys)
          }}
        />)
      }
    </Tabs.TabPane>
  }


  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem",paddingRight:"1%"
    }}>

      <Modal title="项目发布" open={ifshow_fb} okText="发布" cancelText="取消" onOk={() => { handleFb() }} onCancel={() => { setifshow_fb(false) }}>
        <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap" }}>
          <div style={{ width: "25%", marginBottom: "2vh" }}><span style={{ color: "red" }}>*</span>发布类型： </div>
          <div style={{ width: "70%", marginBottom: "2vh" }}>
            <Radio.Group value={fblx} onChange={(e) => { setFblx(e.target.value) }}>
              <Radio value={"立即发布"}>立即发布</Radio>
              <Radio value={"定时发布"}>定时发布</Radio>
            </Radio.Group>
          </div>
          <div style={{ width: "25%", marginBottom: "2vh", display: fblx == "立即发布" ? "none" : "block" }}><span style={{ color: "red" }}>*</span>发布时间： </div>
          <div style={{ width: "70%", marginBottom: "2vh", display: fblx == "立即发布" ? "none" : "block" }}>
            <DatePicker format={"YYYY-MM-DD HH:mm"} locale={locale} onChange={(date, dateString) => { setFbsj(dateString) }} showTime />
          </div>
          <div style={{ width: "25%", marginBottom: "2vh" }}><span style={{ color: "red" }}>*</span>应标截止时间： </div>
          <div style={{ width: "70%", marginBottom: "2vh" }}>
            <DatePicker format={"YYYY-MM-DD HH:mm"} locale={locale} onChange={(date, dateString) => { setYbjzsj(dateString) }} showTime />
          </div>
        </div>
      </Modal>

      <Modal title="项目竞价发布" open={ifshow_fb_jj} okText="发布" cancelText="取消" onOk={() => { handleFb_jj() }} onCancel={() => { setifshow_fb_jj(false) }}>
        <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap" }}>
          <div style={{ width: "25%", marginBottom: "2vh" }}><span style={{ color: "red" }}>*</span>发布类型： </div>
          <div style={{ width: "70%", marginBottom: "2vh" }}>
            <Radio.Group value={fblx_jj} onChange={(e) => { setFblx_jj(e.target.value) }}>
              <Radio value={"立即发布"}>立即发布</Radio>
              <Radio value={"定时发布"}>定时发布</Radio>
            </Radio.Group>
          </div>
          <div style={{ width: "25%", marginBottom: "2vh", display: fblx_jj == "立即发布" ? "none" : "block" }}><span style={{ color: "red" }}>*</span>开标时间： </div>
          <div style={{ width: "70%", marginBottom: "2vh", display: fblx_jj == "立即发布" ? "none" : "block" }}>
            <DatePicker format={"YYYY-MM-DD HH:mm"} locale={locale} onChange={(date, dateString) => { setKbsj(dateString) }} showTime />
          </div>
          {/* <div style={{ width: "25%", marginBottom: "2vh" }}><span style={{ color: "red" }}>*</span>投标截止时间： </div>
          <div style={{ width: "70%", marginBottom: "2vh" }}>
            <DatePicker format={"YYYY-MM-DD HH:mm"} locale={locale} onChange={(date, dateString) => { setTbjzsj(dateString) }} showTime />
          </div> */}
        </div>
      </Modal>



      <div style={styles.kshcontainer}>
        <div style={{
          width: "99vw", height: "", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
          paddingLeft: "1vw",paddingRight:"1vw"
        }}>

          <div style={styleobj.linestyleflex}>
            <span style={{ fontSize: "0.8rem", fontWeight: "500" }}>工具栏</span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            {/* <span style={{ fontSize: "0.7rem", fontWeight: "800" }}>项目名称：</span>
            <Input style={{ width: "200px" }} value={xmmc} onChange={(e) => setXmmc(e.target.value)} />  &nbsp; &nbsp;
            <span style={{ fontSize: "0.7rem", fontWeight: "800" }}>招标品类：</span>
            <Input style={{ width: "200px" }} value={zbpl} onChange={(e) => setZbpl(e.target.value)} />  &nbsp; &nbsp; */}
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
              <ReloadOutlined />刷 新</Button>
            {/* &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { setXmmc(""); setZbpl("") }}>
              <ReloadOutlined />重 置</Button> */}
            &nbsp;{JSON.parse(storage.anpz).find(item => item.key == "xm")?.listAnpz?.showAdd && <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleadd}>
              <PlusSquareOutlined />新 增</Button>}
            {/* &nbsp;{JSON.parse(storage.anpz).find(item => item.key == "xm")?.listAnpz?.showSh && <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleTjsh}>
              <DiffOutlined />发起审核</Button>} */}
            {/* &nbsp;{JSON.parse(storage.anpz).find(item => item.key == "xm")?.listAnpz?.showYb && <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { selectedRows.length == 1 ? setifshow_fb(true) : openNotification_util("请选择要一条邀标发布的项目！") }}>
              <UserAddOutlined />邀 标</Button>}
            &nbsp;{JSON.parse(storage.anpz).find(item => item.key == "xm")?.listAnpz?.showXj && <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { selectedRows.length == 1 ? setifshow_fb(true) : openNotification_util("请选择要一条询价发布的项目！") }}>
              <EditOutlined />询 价</Button>} */}
            &nbsp;{JSON.parse(storage.anpz).find(item => item.key == "xm")?.listAnpz?.showJjfb && <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { selectedRows.length == 1 ? setifshow_fb_jj(true) : openNotification_util("请选择要一条竞价发布的项目！") }}>
              <AppstoreOutlined />竞价发布</Button>}
            {/* &nbsp;{JSON.parse(storage.anpz).find(item => item.key == "xm")?.listAnpz?.showZb && <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { selectedRows.length == 1 ? handleZb(selectedRows[0]) : openNotification_util("请选择要一条中标设置的项目！") }}>
              <EditOutlined />中 标</Button>} */}
            {/* &nbsp;{JSON.parse(storage.anpz).find(item => item.key == "xm")?.listAnpz?.showZb && <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { selectedRows.length == 1 ? handleKb(selectedRows[0]) : openNotification_util("请选择要一条开标设置的项目！") }}>
              <SelectOutlined />淘 汰</Button>} */}
            {/* &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handledelete}>
              <MinusSquareOutlined /> 删 除</Button> */}
          </div>

          <div style={{ width: "100%", height: "0.3vw", backgroundColor: "#F1F1F1" }}></div>
          {ifshow && <Sortable_new tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
            storageName={`Pc_zyjj_list_${storage.userid}`} style={{ position: 'absolute', right: '2vw', top: '1.2rem', fontSize: "1.5rem" }}
            initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage[`Pc_zyjj_list__initsize_${storage.userid}`] = data; }}
          />}
          <Tabs defaultActiveKey="1" className='task-tabs' >
            {TabPaneItem("全部", addkey_for_mxdata(JSON.parse(JSON.stringify(listdata))), columnarr, "1")}
            {TabPaneItem("待发布", addkey_for_mxdata(listdata.filter(item => item.xmzt == "待发布")), columnarr, "2")}
            {TabPaneItem("待应标", addkey_for_mxdata(listdata.filter(item => item.xmzt == "待应标")), columnarr, "3")}
            {/* {TabPaneItem("评标中", addkey_for_mxdata(listdata.filter(item => item.xmzt == "评标中")), columnarr, "4")} */}
            {TabPaneItem("待竞价", addkey_for_mxdata(listdata.filter(item => item.xmzt == "待竞价")), columnarr, "5")}
            {TabPaneItem("竞价中", addkey_for_mxdata(listdata.filter(item => item.xmzt == "竞价中")), columnarr, "6")}
            {TabPaneItem("竞价结束", addkey_for_mxdata(listdata.filter(item => item.xmzt == "竞价结束")), columnarr, "7")}
            {TabPaneItem("已流标", addkey_for_mxdata(listdata.filter(item => item.xmzt == "已流标")), columnarr, "8")}
          </Tabs>

        </div>

      </div>
    </div>
  )
}


export default Zyjj_list


var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },


  kshcontainer: {
    width: "100%", minHeight: "40vh", position: "absolute", top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
    color: "black"
  },
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem", marginTop: "0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}